<?php

namespace app\common\controller;

use app\common\controller\Common;
use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend;

/**
 * 对接企业微信api
 */
class QyApi
{
    protected $corpid = 'wwb75648f6c897ad4e';
    protected $corpsecret = 'DnomtluJsVbYy5tpXnUb2c0oTOiqGqFELNgDn-UOfYc';

    public function __construct(){
        if(time() > session('qy_access_token_add_time') + 7000 || !session('qy_access_token')){
            //获取企业内部应用的access_token，access_token的有效期为7200秒（2小时）
            $res = self::gettoken();
            if($res['errcode'] == 0){
                session('qy_access_token', $res['access_token']);
                session('qy_access_token_add_time', time());
            }
        }
    }

    /**
     * 获取企业内部应用的access_token
     */
    private function gettoken()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$this->corpid}&corpsecret={$this->corpsecret}";
        $res = Common::curl($url);
        return $res;
    }

    /**
     * 获取部门列表
     */
    public function department_list($department_id)
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . session('qy_access_token') . "&id=" . $department_id;
        $res = Common::curl($url);
        return $res;
    }

    /**
     * 获取部门成员详情
     */
    public function user_list()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=".session('qy_access_token')."&department_id=1&fetch_child=1";
        $res = Common::curl($url);
        return $res;
    }

    /**
     * 获取打卡记录数据
     */
    public function getcheckindata($data)
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=" . session('qy_access_token');
        $res = Common::curl($url, $data, 'post');
        return $res;
    }

    /**
     * 发送应用消息
     */
    public function message_send($data)
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . session('qy_access_token');
        $res = Common::curl($url, $data, 'post');
        return $res;
    }
}